import { message } from 'ant-design-vue'
import { storage } from 'g6-fn'
import { NavigationGuardNext, RouteLocationNormalized } from 'vue-router'

import { checkKey } from '@/directives/auth'
import { useUserInfoStore } from '@/store'

import router from './index'
// 路由白名单
export const whiteList = [
  '/login',
  '/invite2Join',
  '/test',
  '/success',
  '/bind-tel',
  '/find-password',
  '/register',
  '/updateemail',
  '/login-mid-page',
  '/login-wechat',
  '/middle-page',
  '/admin',
  '/admin/aigc-admin/teacher',
  '/admin/aigc-admin/students-and-classes',
  '/admin/aigc-admin/drawing-record',
  '/admin/students-and-classes/list',
  '/logout'
]
// 路由跳转前 判断是否需要登录
router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
  console.log(`从${from.path}跳转到${to.path}`)

  if (whiteList.includes(to.path)) {
    return next()
  }

  const token = storage.get('token')
  if (token) {
    const hasToRouteAuth = checkKey((to.meta.auth as string | string[]) || '')
    if (!hasToRouteAuth) {
      message.error('访问地址错误')
      next('/')
      return
    }
    return next()
  } else {
    next('/login')
  }
})

router.afterEach((to: RouteLocationNormalized, from: RouteLocationNormalized) => {
  const { selectAndLink, closeLink } = useUserInfoStore()
  const token = storage.get('token')
  console.log(`从${from.path}跳转到${to.path}  after`)

  if (whiteList.includes(to.path)) {
    closeLink()
    return
  }
  selectAndLink(token)
})

router.onError(err => {
  const isProd = process.env.NODE_ENV === 'production'
  if (isProd) {
    console.log('路由异常' + err)
    // 刷新windows
    window.location.reload()
  }
})
